from app import db

class BaseModel(db.Model):
    __abstract__ = True #当前类只是被继承，不会直接执行
    id = db.Column(db.Integer,primary_key = True,autoincrement = True)

    def save(self):
        db.session.add(self)
        db.session.commit()

    def delete(self):
        db.session.delete(self)
        db.session.commit()

    def update(self):
        db.session.commit()

class BuMen(BaseModel):
    __tablename__ = "department"
    b_name =  db.Column(db.String(32))

    b_zhiwei = db.relationship(
        "ZhiWei",
        backref = "zhi_bumen"
    )
    b_yuangong = db.relationship(
        "YuanGong",
        backref="yuan_bumen"
    )


class ZhiWei(BaseModel):
    __tablename__ = "position" #定义表名，默认表名是类名的小写
    z_name = db.Column(db.String(32))

    z_bumen = db.Column(db.Integer,db.ForeignKey("department.id"))
    z_yuangong = db.relationship(
        "YuanGong",
        backref="yuan_zhiwei"
    )

    def __repr__(self):
        return self.z_name

class YuanGong(BaseModel):
    __tablename__ = "person"
    y_name = db.Column(db.String(32))

    y_zhiwei = db.Column(db.Integer,db.ForeignKey("position.id"))
    y_bumen = db.Column(db.Integer,db.ForeignKey("department.id"))


db.create_all()

#插入部门
# b = BuMen()
# b.b_name = "秘书部"
# b.save()
# b = BuMen()
# b.b_name = "董事会"
# b.save()
#插入职位
# z = ZhiWei()
# z.z_name = "秘书长"
# z.z_bumen = 1
# z.save()
#
# z = ZhiWei()
# z.z_name = "董事长"
# z.z_bumen = 2
# z.save()
#插入秘书长职位员工

y = YuanGong()
b = BuMen.query.get(1)
y.y_name = "小王"
y.yuan_bumen = b
print(b.b_zhiwei)
y.yuan_zhiwei = b.b_zhiwei[0]
y.save()



